package com.its.net.udp.server.handler;

import cn.hutool.core.util.RandomUtil;
import com.its.common.net.core.dto.GenericNetDTO;
import com.its.common.net.server.handler.BaseServerUdpHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Xiaxiaopeng
 * @description 功能描述
 * @create 2023/5/31 16:02
 */
@Slf4j
@Component
public class CustomHandler extends BaseServerUdpHandler {

    @Override
    public void handleData(ChannelHandlerContext ctx, GenericNetDTO<DatagramPacket> data) {
        try {
            Thread.sleep(RandomUtil.randomLong(10, 500));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("服务端接受消息，发送方[{}], 内容:{}", data.getSender(), new String(extract2bytes(data.getData())));

        //给客户端返回一个
        String replayBody = "客户端你给我少发点, "+ LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        InetSocketAddress address = data.getSender().getInetSocketAddress();
        if (null != address) {
            DatagramPacket replay = new DatagramPacket(Unpooled.copiedBuffer(replayBody.getBytes()), address);
            ctx.writeAndFlush(replay);
        }
    }
}
